﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Web.Oauth2.impl
{
    public class WeiboConnector : OauthConnector
    {
        Dictionary<string, string> genders = new Dictionary<string, string>();

        public WeiboConnector(String appkey, String appSecret) : base(appkey, appSecret)
        {
            Type = OauthType.weibo;
            genders.Add("m", "male");
            genders.Add("f", "female");
            genders.Add("n", "unkown");
        }

        protected override String CreateAuthorizeUrl(String state)
        {
            StringBuilder urlBuilder = new StringBuilder("https://api.weibo.com/oauth2/authorize?");
            urlBuilder.Append("scope=email");
            urlBuilder.Append("&client_id=" + ClientId);
            urlBuilder.Append("&redirect_uri=" + RedirectUri);
            urlBuilder.Append("&state=" + state);

            return urlBuilder.ToString();
        }

        protected override OauthUser GetOauthUser(String code)
        {
            StringBuilder urlBuilder = new StringBuilder("https://api.weibo.com/oauth2/access_token?");
            urlBuilder.Append("grant_type=authorization_code");
            urlBuilder.Append("&client_id=" + ClientId);
            urlBuilder.Append("&client_secret=" + ClientSecret);
            urlBuilder.Append("&redirect_uri=" + RedirectUri);
            urlBuilder.Append("&code=" + code);

            String url = urlBuilder.ToString();
            String httpString = HttpGet(url);
            var jObject = JObject.Parse(httpString);

            String accessToken = jObject["access_token"].ToString();
            String uid = jObject["uid"].ToString();

            url = "https://api.weibo.com/2/users/show.json?" + "access_token=" + accessToken + "&uid=" + uid;

            httpString = HttpGet(url);
            jObject = JObject.Parse(httpString);

            OauthUser user = new OauthUser();
            user.Avatar = jObject["avatar_large"].ToString();
            user.Nickname = jObject["screen_name"].ToString();
            user.OpenId = jObject["id"].ToString();
            user.Gender = genders[jObject["gender"].ToString()];
            user.Source = Type.ToString();
            return user;
        }


        public override AccessToken GetAccessToken(String code)
        {

            return null;
        }

        public override AccessToken RefreshAccessToken(string refresh_token)
        {
            throw new NotImplementedException();
        }
    }
}
